package com.briup.day35;

import java.io.File;
import java.util.Scanner;

public class SearchDemo2 {
	static String searchName;
	static boolean match;
	static boolean casee;  //文件名大小写
	
	static int filecount;
	static int dircount;
	
	static boolean findHidden; 	// 是否查找隐藏文件或目录
	static boolean findDir; 	// 是否查找目录

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入您要搜索的文件名：");
		searchName = sc.nextLine();
		System.out.println("是否要进行模糊匹配?Y/N");
		String s1 = sc.nextLine();
		System.out.println("文件名大小是否敏感?Y/N");
		String s2 = sc.nextLine();
		if ("Y".equals(s1.toUpperCase())) {
			match = true ;
		}
		if ("Y".equals(s2.toUpperCase())) {
			casee = true;
		}
		
		
		MyPredicate<File> rules = new MyPredicate<File>() {
			
			@Override
			public boolean test(File file) {
				if (!findHidden && file.isFile()) {
					return false;
				}
				if(!findDir && file.isDirectory()) {
					return false;
				}
				if (match) {
					
						return casee ? 
								(file.getName().contains(searchName)):
								(file.getName().toUpperCase().contains(searchName.toUpperCase()));
								
				}else {

						return casee?
								(file.getName().equals(searchName)):
								(file.getName().toUpperCase().equals(searchName.toUpperCase()));
							
					
				}
				
			
			}
		};
		File dir = new File("src");
		
		long t1 = System.currentTimeMillis();
		searchFile(dir,rules);
		long t2 = System.currentTimeMillis();
		System.out.println("搜索完成。共找到符合要求的文件" 
				+ filecount + "个，目录" + dircount + "个，"
				+ "共耗时" + (t2 - t1) + "毫秒。");
				
	}
	
	public static void searchFile(File file , MyPredicate<File> rules) {
		File[] files = null;
		
		if (file == null || (files = file.listFiles()) == null)
			return;
		
		for (File f : files) {
			if (rules.test(f)) {
				System.out.println(f);
				if (f.isFile())
					filecount++;
				else 
					dircount++;
			}
			
			searchFile(f,rules); // 递归调用
		}
		
	}
}
